export const inBrowser = typeof window !== "undefined";

const root = inBrowser ? window : global;

let prev = Date.now();

// fn: FrameRequestCallback
function rafPolyfill(fn) {
  const curr = Date.now();
  const ms = Math.max(0, 16 - (curr - prev));
  const id = setTimeout(fn, ms);
  prev = curr + ms;
  return id;
}

// fn: FrameRequestCallback
export function raf(fn) {
  const requestAnimationFrame = root.requestAnimationFrame || rafPolyfill;
  return requestAnimationFrame.call(root, fn);
}
// id: number
export function cancelRaf(id) {
  const cancelAnimationFrame = root.cancelAnimationFrame || root.clearTimeout;
  cancelAnimationFrame.call(root, id);
}

// double raf for animation
// fn: FrameRequestCallback
export function doubleRaf(fn) {
  raf(() => raf(fn));
}
